package com.hadluo.qq.server.service.impl;

import com.hadluo.qq.server.mapper.MessageMapper;
import com.hadluo.qq.server.entity.Message;
import com.hadluo.qq.server.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Override
    @Transactional
    public void saveMessage(Message message) {
        messageMapper.insert(message);
    }

    @Override
    public List<Message> getHistoryMessages(Long userId1, Long userId2, Integer page, Integer size) {
        // 计算分页偏移量
        int offset = (page - 1) * size;
        return messageMapper.selectChatHistory(userId1, userId2).stream()
                .skip(offset)
                .limit(size)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void markMessageAsRead(Long messageId) {
        messageMapper.updateMessageStatus(messageId, 1);
    }

    @Override
    public int getUnreadMessageCount(Long userId) {
        return messageMapper.countUnreadMessages(userId);
    }

    @Override
    public List<Message> getUnreadMessages(Long userId) {
        return messageMapper.selectUnreadMessages(userId);
    }

    @Override
    public List<Message> getChatHistory(Long userId1, Long userId2, int limit) {
        return messageMapper.selectLatestMessages(userId1, userId2, limit);
    }
}